package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFegin;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealNameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUserRealNameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealNameService {

    /**
     * 用户认证分页列表
     * @param authDTO
     * @return
     */
    @Override
    public ResponseResult list(AuthDTO authDTO) {
        //校验请求参数
        if(authDTO == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验分页参数
        authDTO.checkParam();
        Page<ApUserRealname> page = new Page<>(authDTO.getPage(),authDTO.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();

        //如果状态码 不为空的话就按照状态码进行查询
        if(authDTO.getStatus() != null){
            wrapper.eq(ApUserRealname::getStatus,authDTO.getStatus());
        }
        //进行分页查询
        IPage<ApUserRealname> userRealnameIPage = page(page,wrapper);

        //返回结果
        return new PageResponseResult(authDTO.getPage(),authDTO.getSize(),userRealnameIPage.getTotal(),userRealnameIPage.getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * 根据状态进行审核
     * @param dto
     * @param status  2 审核失败   9 审核成功
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        if(dto == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询当前认证用户是否在app端存在
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getUserId, dto.getId()));
        //查询到为空的话 无效参数
        if (apUserRealname == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户认证信息去查询app端用户表 看是否存在关联用户
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if(apUser == null){
            //如果为空的话 此app用户不存在
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //更新用户认证信息 因为在controller层 就已经通过不同的接口传过来不同的状态参数 这里直接赋值
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        //如果是要驳回的这里还要更新驳回理由
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //如果认证状态为通过的话 就创建自媒体  创建作者
        if(AdminConstants.PASS_AUTH.equals(status)){
            //创建自媒体账户 自媒体账户信息与app用户信息一致
            WmUser wmUser = createWmUser(apUser);
            //创建文章作者
            createArticle(wmUser);
        }
        return ResponseResult.okResult();
    }
    @Autowired
    WemediaFeign wemediaFeign;
    //通过feign接口远程调用 创建自媒体用户
    private WmUser createWmUser(ApUser apUser){
        //远程调用feign接口 根据用户名称去查询 自媒体账户信息
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        if(wmUserResult.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = wmUserResult.getData();
        if(wmUser != null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自媒体用户已存在");
        }
        WmUser wmUser1 = new WmUser();
        wmUser1.setApUserId(apUser.getId());
        wmUser1.setName(apUser.getName());
        wmUser1.setPassword(apUser.getPassword());
        wmUser1.setSalt(apUser.getSalt());
        wmUser1.setImage(apUser.getImage());
        wmUser1.setPhone(apUser.getPhone());
        wmUser1.setStatus(AdminConstants.PASS_AUTH.intValue());
        wmUser1.setType(0);
        wmUser1.setCreatedTime(new Date());
        ResponseResult<WmUser> wmUserResponseResult = wemediaFeign.saveWmUser(wmUser1);
        return wmUserResponseResult.getData();
    }

    @Autowired
    ArticleFegin articleFegin;
    private void createArticle(WmUser wmUser){
        if(wmUser == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //调用feign接口去查询是否有作者信息
        ResponseResult<ApAuthor> feginApAuthorResult = articleFegin.findByUserId(wmUser.getId());
        if(feginApAuthorResult.getCode() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApAuthor author = feginApAuthorResult.getData();
        if(author != null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已存在");
        }
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());

        ResponseResult<ApAuthor> apAuthorResponseResult = articleFegin.saveApAuthor(apAuthor);
        Integer code = apAuthorResponseResult.getCode();
        if(code != 0){
         CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }
}
